//
//  JDUserAccount.swift
//  JDWeiBo
//
//  Created by apple on 15/6/28.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

// CustomStringConvertible 在swift 2.0中变样了····
class JDUserAccount: NSObject, NSCoding {
    
    // 用于调用access_token，接口获取授权后的access token
    var access_token : String
    // access_token的生命周期，单位是秒数。
    var expires_in : NSTimeInterval
    // 当前授权用户的UID
    var uid : String
    // 过期时间
    var expires_in_Date : NSDate
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?

    
    // 初始化
    init(dict : [String : AnyObject]) {
        
        access_token = dict["access_token"] as! String
        
        expires_in = dict["expires_in"] as! NSTimeInterval
        
        uid = dict["uid"] as! String
        
        expires_in_Date = NSDate(timeIntervalSinceNow:expires_in)
    }
    
     /// 加载用户详细信息
    ///  加载用户信息
    func loadUserInfo(finished: (account: JDUserAccount?, error: NSError?) -> ()) {
        
        let params = ["access_token": access_token, "uid": uid]
        
        JDNetworkTools.sharedNetworkTools().GET("2/users/show.json", parameters: params, success: { (_, JSON) -> Void in
            
            let dict = JSON as! [String: AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            // 目前的用户信息才是完整的
            // 保存用户信息
            self.saveAccount()
            
            // 通知调用方，处理完成
            finished(account: self, error: nil)
            
            }) { (_, error) -> Void in
                finished(account: nil, error: error)
        }
    }
    
    /// 打印对象信息 打印对象信息的方法  先遵守 CustomStringConvertible 把方法写完之后在删除 否则会报错（重复定义）
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expires_in_Date", "avatar_large", "name"]
        
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }

    
    /// 保存和加载文件
    // 归档路径swift中的类长量都是使用 static 来定义
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingPathComponent("abc.plist")
    
    // 将当前对象归档保存沙盒
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: JDUserAccount.accountPath!)
    }
    
    // 如果之前没有归档 可能会返回NIL 所以需要判断一下
    class func loadAccount() -> JDUserAccount? {
        
        print("加载账户@@@@")
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? JDUserAccount {
            
             print( NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingPathComponent("abc.plist"))
            
            // 过期日期大于当前日期
            if account.expires_in_Date.compare(NSDate()) == NSComparisonResult.OrderedDescending {

                return account
            }
        }
        return nil
    }
    
    ///  解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_in_Date = aDecoder.decodeObjectForKey("expires_in_Date") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as? String
        
    }
    ///  归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_in_Date, forKey: "expires_in_Date")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
}
































